import {Component, ElementRef, Inject, OnInit, ViewChild} from '@angular/core';
import {
  MAT_DIALOG_DATA, MatDialog, MatDialogRef, MatInput, MatPaginator, MatSelect, MatSnackBar, MatSort,
  MatTableDataSource
} from '@angular/material';
import {OrderService} from '../shared/order.service';
import {Router} from '@angular/router';
import {Order} from '../shared/order.model';
import {ConfirmDialogComponent} from '../../core/confirm-dialog/confirm-dialog.component';
import {APP_CONFIG} from '../../config/app.config';
import {Observable, Subscription, timer} from 'rxjs';

@Component({
  selector: 'app-comment-dialog',
  templateUrl: './comment.dialog.html',
})
export class CommentDialogComponent {

  constructor(
    public dialogRef: MatDialogRef<CommentDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) { }

  onNoClick(): void {
    this.dialogRef.close();
  }
}

// @Component({
//   selector: 'app-confirm-dialog',
//   templateUrl: './confirm.dialog.html',
// })
// export class ConfirmDialogComponent {
//   constructor() {
//   }
// }

@Component({
  selector: 'app-order-list',
  templateUrl: './order-list.component.html',
  styleUrls: ['./order-list.component.css']
})
export class OrderListComponent implements OnInit {
  // displayedColumns = ['detail', 'order', 'service', 'user', 'employee', 'status', 'oper'];
  displayedColumns = ['detail', 'order', 'employee', 'status', 'oper'];
  dataSource: MatTableDataSource<Order>;
  // orders: BehaviorSubject<Order[]> = new BehaviorSubject<Order[]>([]);
  orders: Order[] = [];
  get selectedValueStatusFilter(): string {
    return this.orderService.selectedValueStatusFilter;
  }
  set selectedValueStatusFilter(f: string) {
    this.orderService.selectedValueStatusFilter = f;
  }

  get inputValueUserMobileFilter(): string {
    return this.orderService.inputValueUserMobileFilter;
  }
  set inputValueUserMobileFilter(f: string) {
    this.orderService.inputValueUserMobileFilter = f;
  }

  get inputValueOrderNumberFilter(): string {
    return this.orderService.inputValueOrderNumberFilter;
  }
  set inputValueOrderNumberFilter(f: string) {
    this.orderService.inputValueOrderNumberFilter = f;
  }
  // selectedValueStatusFilter: string;
  // inputValueUserMobileFilter: string;
  // inputValueOrderNumberFilter: string;

  lastEditOrderProblem: string;

  unassignedDisabled = false;
  assignDisabled = false;
  refundDisabled = false;
  finishRefundDisabled = false;
  deleteDisabled = false;
  problemDisabled = false;
  cancelDisabled = false;

  days = 30;
  // private timer;
  private subscription: Subscription;

  private originOrderIdList = [];
  private newOrderIdList = [];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild('audioOption') audioPlayerRef: ElementRef;

  constructor(private orderService: OrderService,
              private router: Router,
              private snackBar: MatSnackBar,
              private dialog: MatDialog) {
  }

  loadOrderList() {
    this.orderService.getOrderList(this.days).subscribe((value) => {
      this.orders = <Order[]><any>value;
      this.dataSource = new MatTableDataSource<Order>(this.orders);
      this.refreshTable();
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      this.orders.map(elem => this.newOrderIdList.push(elem.orderId));
      const differences = this.orderService.detectOrderListChange(this.originOrderIdList, this.newOrderIdList);
      if (differences.length > 0) {
        this.audioPlayerRef.nativeElement.play();
      }
    }, (value) => {
      this.openSnackBar('获取订单列表错误!', '');
    });
  }
  ngOnInit() {
    const tt = timer(0, 30000);
    this.subscription =  tt.subscribe( t => {
      this.originOrderIdList = [];
      this.newOrderIdList = [];
      this.orders.map( elem => this.originOrderIdList.push(elem.orderId));
      this.loadOrderList();
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
    // this.subscribtion.unsubscribe();
  }
  selectRow(target, row) {
    this.orderService.currentOrder = row;
    this.router.navigate(['orders/', row.orderId]);
  }
  clearFilters(filterName: string) {
    if (filterName === 'statusFilter') {
      this.inputValueUserMobileFilter = '';
      this.inputValueOrderNumberFilter = '';
    }
    if (filterName === 'userMobileFilter') {
      this.selectedValueStatusFilter = '';
      this.inputValueOrderNumberFilter = '';
    }
    if (filterName === 'orderNumberFilter') {
      this.selectedValueStatusFilter = '';
      this.inputValueUserMobileFilter = '';
    }
  }
  applyStatusFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filterPredicate = (data: Order, filter: string) => data.status.toLowerCase().indexOf(filterValue) !== -1;
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.clearFilters('statusFilter');
  }
  applyOrderNumberFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filterPredicate = (data: Order, filter: string) => data.orderNumber.toLowerCase().indexOf(filterValue) !== -1;
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.clearFilters('orderNumberFilter');
  }
  applyUserMobileFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filterPredicate = (data: Order, filter: string) => data.user.phoneNumber.toLowerCase().indexOf(filterValue) !== -1;
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.clearFilters('userMobileFilter');
  }
  onClearClicked(target) {
    this.inputValueOrderNumberFilter = '';
    this.inputValueUserMobileFilter = '';
    this.selectedValueStatusFilter = '';
    this.refreshTable();
  }
  onProblemClicked(target, row) {
    this.problemDisabled = true;
    const dialogRef = this.dialog.open(CommentDialogComponent, {
      width: '250px',
      data: { lastEditOrderProblem: this.lastEditOrderProblem }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.orderService.currentOrder = row;
        const updateOrder = this.orderService.currentOrder;
        updateOrder.remarks = updateOrder.remarks + ' [运维]: ' + result;
        // updateOrder.status = 'problem';
        updateOrder.statusCode = 0;
        this.orderService.updateOrder(String(updateOrder.orderId), updateOrder).subscribe(value => {
            this.regainAndRefresh(String(updateOrder.orderId));
            this.openSnackBar('更新成功！', '');
            this.problemDisabled = false;
          },
          value => {
            this.openSnackBar('更新失败！', '');
            this.problemDisabled = false;
          });
      } else {
        this.problemDisabled = false;
      }
    });
  }
  onDeleteClicked(target, row) {
    this.deleteDisabled = true;
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.orderService.currentOrder = row;
        const orderId = this.orderService.currentOrder.orderId;
        this.orderService.deleteOrder(String(orderId)).subscribe( value => {
          if (value) {
            const index = this.orders.findIndex( elem => elem.orderId === orderId);
            this.dataSource.data.splice(index, 1);
            this.refreshTable();
            this.openSnackBar('订单已删除！', '');
            this.deleteDisabled = false;
          } else {
            this.openSnackBar('删除订单失败！', '');
            this.deleteDisabled = false;
          }
        });
      } else {
        this.deleteDisabled = false;
      }
    });
  }
  onCancelClicked(target, row) {
    this.cancelDisabled = true;
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.orderService.currentOrder = row;
        const updateOrder = this.orderService.currentOrder;
        // updateOrder.status = 'cancelled';
        updateOrder.statusCode = -1;
        let washerId = 0;
        if (row.washerInfo) {
          washerId = row.washerInfo.id;
        }
        this.orderService.cancelOrder(String(updateOrder.orderId), String(washerId)).subscribe( value => {
            this.regainAndRefresh(String(updateOrder.orderId));
            this.openSnackBar('更新成功！', '');
            this.cancelDisabled = false;
          },
          value => {
            this.openSnackBar('更新失败！', '');
            this.cancelDisabled = false;
          });
      } else {
        this.cancelDisabled = false;
      }
    });
  }
  onUnassignedClicked(target, row) {
    this.unassignedDisabled = true;
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.orderService.currentOrder = row;
        const updateOrder = this.orderService.currentOrder;
        // updateOrder.status = 'unassigned';
        updateOrder.statusCode = 20;

        this.orderService.updateOrder(String(updateOrder.orderId), updateOrder).subscribe( value => {
            this.regainAndRefresh(String(updateOrder.orderId));
            this.openSnackBar('更新成功！', '');
            this.unassignedDisabled = false;
          },
          value => {
            this.openSnackBar('更新失败！', '');
            this.unassignedDisabled = false;
          });
      } else {
        this.unassignedDisabled = false;
      }
    });
  }
  onAssignClicked(target, row) {
    this.orderService.currentOrder = row;
    this.router.navigate(['orders/', row.orderId]);
  }
  onRefundClicked(target, row) {
    this.refundDisabled = true;
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.orderService.currentOrder = row;
        const updateOrder = this.orderService.currentOrder;
        updateOrder.remarks += ' [运维]: 该订单退款处理中！';
        // updateOrder.status = 'refunding';
        updateOrder.statusCode = 50;
        this.orderService.updateOrder(String(updateOrder.orderId), updateOrder).subscribe( value => {
            this.regainAndRefresh(String(updateOrder.orderId));
            this.openSnackBar('更新成功！', '');
            this.refundDisabled = false;
          },
          value => {
            this.openSnackBar('更新失败！', '');
            this.refundDisabled = false;
          });
      } else {
        this.refundDisabled = false;
      }
    });
  }
  onFinishRefundClicked(target, row) {
    this.finishRefundDisabled = true;
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.orderService.currentOrder = row;
        const updateOrder = this.orderService.currentOrder;
        updateOrder.remarks += ' [运维]: 该订单已完成退款！';
        // updateOrder.status = 'refunded';
        updateOrder.statusCode = -1;
        this.orderService.updateOrder(String(updateOrder.orderId), updateOrder).subscribe( value => {
            this.regainAndRefresh(String(updateOrder.orderId));
            this.openSnackBar('更新成功！', '');
            this.finishRefundDisabled = false;
          },
          value => {
            this.openSnackBar('更新失败！', '');
            this.finishRefundDisabled = false;
          });
      } else {
        this.finishRefundDisabled = false;
      }
    });
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
  regainAndRefresh(orderId: string) {
    this.orderService.getOrderDetail(orderId).subscribe( order => {
      console.log('regain order successful...');
      const newOrder = order;
      const index = this.orders.findIndex(elem => elem.orderId === newOrder.orderId);
      this.orders[index] = newOrder;
      this.refreshTable();
    }, order => {
      console.log('regain order failed...');
    });
  }
  // If you don't need a filter or a pagination this can be simplified, you just use code from else block
  private refreshTable() {
    this.dataSource.filter = '';
    if (this.selectedValueStatusFilter !==  '' ) {
      this.dataSource.filterPredicate = (data: Order, filter: string) =>
        data.status.trim().toLowerCase().indexOf(this.selectedValueStatusFilter.trim().toLowerCase()) !== -1;
      this.dataSource.filter = this.selectedValueStatusFilter;
    } else if (this.inputValueUserMobileFilter !== '') {
      this.dataSource.filterPredicate = (data: Order, filter: string) =>
        data.user.phoneNumber.trim().toLowerCase().indexOf(this.inputValueUserMobileFilter.trim().toLowerCase()) !== -1;
      this.dataSource.filter = this.inputValueUserMobileFilter;
    } else if (this.inputValueOrderNumberFilter !== '') {
      this.dataSource.filterPredicate = (data: Order, filter: string) =>
        data.orderNumber.trim().toLowerCase().indexOf(this.inputValueOrderNumberFilter.trim().toLowerCase()) !== -1;
      this.dataSource.filter = this.inputValueOrderNumberFilter;
    }
  }
}

